<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<html>
<head>
    <title>书籍登到-书籍验收</title>
    <meta name="decorator" content="default"/>
    <script src="${ctxStatic}/lodop/LodopFuncs.js" type="text/javascript"></script>
    <script type="text/javascript">
        window.parent.refresh = false;
        $(document).ready(function(){
            $('#isbn_0').focus();
        });
        var batchId = '${bkPurchaseBatch.batchId}';
        function page(n, s) {
            $("#pageNo").val(n);
            $("#pageSize").val(s);
            $("#searchForm").submit();
            return false;
        }
        var index = 11;
        function addBatchDetail() {
            var html = "<tr style='cursor: pointer;' ondblclick='openBookInfoEdit(" + index + ")' id='tr_" + index + "'>" +
                    "<td><input type='radio' name='book' /></td>" +
                    "<td width='150'>" +
                    "<input id='isbn_" + index + "' style='width: 150px;' name='isbn' onkeypress='EnterPress(this,event)' >" +
                    "<input id='bkId_" + index + "' name='bkId' type='hidden'>" +
                    "</td>" +
                    "<td></td><td></td><td></td><td></td><td></td><td></td>" +
                    "<td></td>" +
                    "<td width='100'><input name='price' size='10' width='10' readonly style='width: 100px;background-color: #eeeeee;'></td>" +
                    "<td></td>" +
                    "<td width='200'>" +
                    "<span></span>" +
                    "<a href='javascript:deleteBookInfo(\"tr_" + index + "\")'>删除</a>&nbsp;&nbsp;" +
                    "</td>" +
                    "</tr>";
            $("#details").append(html);
            $("#isbn_"+ index).focus();
            index++;
        }
        function openBookInfoEdit(index) {
            var bkId = $("#bkId_" + index).val();
            top.$.jBox.open("iframe:${ctx}/book/manage/get?pop=true&bkId=" + bkId, "修改图书", 1200, 750, {
                buttons: {"关闭": true}, loaded: function (h) {
                    h.find("iframe")[0].contentWindow.setupPopUp();
                    $(".jbox-content", top.document).css("overflow-y", "hidden");
                }, closed: function () {
                    $.ajax({
                        type: "POST",
                        url: "${ctx}/book/manage/getBookInfoById",
                        data: {bkId: bkId},
                        dataType: "json",
                        success: function (data) {
                            var obj = document.getElementById("isbn_" + index);
                            setTdBookInfo(obj, data);
                        }
                    });
                }
            });
        }
        function openBookInfoAdd(obj) {
            var isbn = $(obj).val();
            top.$.jBox.open("iframe:${ctx}/book/manage/get?pop=true&isbn=" + isbn, "修改图书", 1200, 680, {
                buttons: {"关闭": true}, loaded: function (h) {
                    h.find("iframe")[0].contentWindow.setupPopUp();
                    $(".jbox-content", top.document).css("overflow-y", "hidden");
                }, closed: function () {
                    $.ajax({
                        type: "POST",
                        url: "${ctx}/book/manage/getBookInfoByISBN",
                        data: {bookISBN: isbn},
                        dataType: "json",
                        success: function (data) {
                            setTdBookInfo(obj, data);
                        }
                    });
                }
            });
        }

        function searchBook(obj) {
            var isbn = $(obj).val();
            $.ajax({
                type: "POST",
                url: "${ctx}/book/manage/getByIsbn",
                data: {isbn: isbn},
                dataType: "json",
                success: function (data) {
                    if (data == null || data == "") {
                        openBookInfoAdd(obj);
                    } else {
                        if (data.length >= 2) {
                            top.$.jBox.open("iframe:${ctx}/book/manage/selectBook?isbn=" + isbn, "选择图书", 800, 500, {
                                buttons: {"确定": "ok", "关闭": true}, submit: function (v, h, f) {
                                    if (v == "ok") {
                                        var bkId = h.find("iframe")[0].contentWindow.getBookId();
                                        for (var i = 0; i < data.length; i++) {
                                            var result = data[i];
                                            if (result.id == bkId) {
                                                setTdBookInfo(obj, result);
                                                return;
                                            }
                                        }
                                    }
                                }, loaded: function (h) {
                                    $(".jbox-content", top.document).css("overflow-y", "hidden");
                                }, closed: function () {
                                    var bkId = window.parent.bkId;
                                    for (var i = 0; i < data.length; i++) {
                                        var result = data[i];
                                        if (result.id == bkId) {
                                            setTdBookInfo(obj, result);
                                            return;
                                        }
                                    }
                                }
                            });
                        } else {
                            setTdBookInfo(obj, data[0]);
                        }
                    }
                }
            });
        }

        function setTdBookInfo(obj, data) {
            var bkId = data.id;
            if(bkId === '' || bkId === 0 || bkId === undefined){
                return;
            }
            $(".td_noselect").each(function () {
                $(this).removeClass("td_select");
            });

            var usedBook = $("#bkId_" + bkId);
            if (usedBook.val() && usedBook.val() != "") {
                var usedIsbn = usedBook.parent().next();
                usedIsbn.addClass("td_select");
                $('html,body').animate({scrollTop: usedIsbn.offset().top}, 800);
                $(obj).parent().parent().remove();
            } else {
                $.ajax({
                    type: "POST",
                    url: "${ctx}/book/purchase/findDetailByBkId",
                    data: {bkId: bkId},
                    dataType: "json",
                    async: false,
                    success: function (detail) {
                        if (detail) {
                            addDetail(detail);
                            $(obj).parent().parent().remove();
                        } else {
                            var tempStr = "";
                            if (data.othername != null && data.othername != '') {
                                tempStr = "-" + data.othername;
                            }
                            var bookname = data.bookname + tempStr;
                            var author = data.author;
                            var classcode = data.classcode;
                            var books = data.books;
                            var booksNum = data.booksNum;
                            var publisher = data.publisher;
                            var pubdate = data.pubdate;
                            var price = data.price;
                            $(obj).siblings().val(bkId);
                            $(obj).parents("td").siblings().each(function (i) {
                                if (i == 1) {
                                    $(this).html(classcode);
                                }
                                else if (i == 2) {
                                    $(this).html(bookname);
                                }
                                else if (i == 3) {
                                    $(this).html(author);
                                }
                                else if (i == 4) {
                                    $(this).html(books);
                                }
                                else if (i == 5) {
                                    $(this).html(booksNum);
                                }
                                else if (i == 6) {
                                    $(this).html(publisher);
                                }
                                else if (i == 7) {
                                    $(this).html(pubdate);
                                }
                                else if (i == 8) {
                                    $(this).find("input").val(price);
                                }
                                else if (i == 10) {
                                    $(this).find("span").html("<a href='javascript:addPurchase(\"" + bkId + "\")'>新增</a>&nbsp;&nbsp;");
                                }
                            });
                            if (bkId) {
                                //addPurchase(id);
                            }
                            else {

                            }
                        }
                    }
                });
            }
            addPurchase(bkId);
        }

        function addDetail(purchaseDetail){
            var html = "<tr>"
                    + "	<td><input id='bkId_" + purchaseDetail.bkId + "' value='" + purchaseDetail.bkId + "' style='display: none;'>" + index + "</td>"
                    + "	<td class='td_noselect td_select'>" + purchaseDetail.bkIsbn + "</td>"
                    + "	<td>" + purchaseDetail.bkClass + "</td>"
                    + "	<td>" + purchaseDetail.bkName + "<c:if test='"+not empty purchaseDetail.othername+"'>-" + purchaseDetail.othername + "</c:if></td>"
                    + "	<td>" + purchaseDetail.author + "</td>"
                    + "	<td>" + purchaseDetail.books + "</td>"
                    + "	<td>" + purchaseDetail.booksNum + "</td>"
                    + "	<td>" + purchaseDetail.publisher + "</td>"
                    + "	<td>" + purchaseDetail.pubdate + "</td>"
                    + "	<td style='text-align: right;'>" + purchaseDetail.discountedPrice + "</td>"
                    + "	<td style='text-align: right;'>" + purchaseDetail.mxArrived + "</td>"
                    + "	<td width='150'>"
                    + "		<a href=\"javascript:addPurchase('" + purchaseDetail.bkId + "')\">新增</a>&nbsp;&nbsp;"
                    + "		<a href=\"javascript:editPurchase('" + purchaseDetail.batchId + "', '" + purchaseDetail.bkId + "','" + purchaseDetail.pbdId + "')\">编辑</a>&nbsp;&nbsp;"
                    + "		<a href=\"javascript:printTagByDetails('" + purchaseDetail.batchId + "', '" + purchaseDetail.bkId + "','" + purchaseDetail.pbdId + "')\">书标打印</a>"
                    + "	</td>"
                    + "</tr>";
            $("#details").append(html);
        }

        function deleteBookInfo(bkId) {
            $("#" + bkId).remove();
        }

        function checkPrice() {
            $("[name='discountedPrice']").each(function () {
                if ($(this) == undefined || $(this).val() == "" || !isFinite($(this).val())) {
                    alertx("输入的【图书价格】信息错误！");
                    return false;
                }
            });
            return true;
        }
        var r = /^[0-9]*[1-9][0-9]*$/;
        function checkMxCnt() {
            $("[name='mxCnt']").each(function () {
                if ($(this) == undefined || $(this).val() == "" || !r.test($(this).val())) {
                    alertx("输入的【采购量】信息错误！");
                    return false;
                }
            });
            return true;
        }
        function checkBatchDate() {
            var flag = true;
            if ($("[name='batchDate']").val() == "") {
                alertx("请选择登到日期！");
                flag = false;
            }
            return flag;
        }
        function submitPurchase() {
            if (checkBatchDate() && checkMxCnt() && checkPrice()) {
                $.ajax({
                    type: "POST",
                    url: "${ctx}/book/purchase/save",
                    data: {
                        batchId: $("#batchId").val(),
                        batchDate: $("#batchDate").val(),
                        remarks: $("#remarks").val(),
                        param: $("#purchaseForm").serialize()
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.code == "0001") {
                            window.location.href = "${ctx}/book/purchase/?repage&batchId=" + data.data;
                            top.$.jBox.tip(data.msg, '提示', {
                                closed: function () {
                                    window.location.href = "${ctx}/book/purchase/?repage&batchId=" + data.data;
                                }
                            });
                            top.$('.jbox-body .jbox-icon').css('top', '55px');

                        } else {
                            alertx("保存信息失败");
                        }
                    }
                });
            }
        }
        function cancelPlan() {
            $.ajax({
                type: "POST",
                url: "${ctx}/book/purchase/cancel",
                data: {
                    batchId: $("#batchId").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.code == "0001") {
                        top.$.jBox.tip(data.msg, '提示', {
                            closed: function () {
                                window.location.href = "${ctx}/book/purchase/?repage&batchId=" + data.data;
                            }
                        });
                        top.$('.jbox-body .jbox-icon').css('top', '55px');

                    } else {
                        alertx("保存信息失败");
                    }
                }
            });
        }

        /**
         * 新增 验收书籍
         * @param bkId
         */
        function addPurchase(bkId) {
            parent.$.jBox.open("iframe:${ctx}/book/purchase/addPurchaseDetail?batchId=${bkPurchaseBatch.batchId}" + "&bkId=" + bkId, "新增验收", 900, 380,{
                        buttons: {}, closed: function () {
                    if(window.parent.refresh){
                        location.reload();
                    }
                    }, loaded: function () {
                        $(".jbox-content", top.document).css("overflow-y", "hidden");
                    }
                    });
        }

        function editPurchase(batchId, bkId, pbdId) {
            parent.$.jBox.open("iframe:${ctx}/book/store/checkList?batch=" + batchId + "&bkId=" + bkId, "编辑验收", 900, 350, {
                buttons: {},
                closed: function () {
                    if(window.parent.refresh){
                        location.reload();
                    }
                }, loaded: function () {
                    $(".jbox-content", top.document).css("overflow-y", "hidden");
                }
            });
        }
        function EnterPress(obj, e,rolnum) { //传入 event
            var e = e || window.event;
            if (e.keyCode == 13) {
                searchBook(obj);
            }
        }
        function refAddBookinfo(isbn) {
            confirmx("没有查询到这本书，请先新增书目！", openBookInfoAdd(isbn));
        }
    </script>
    <style>
        .control-label { width: 120px; } .form-horizontal .controls { margin-left: 140px; overflow-x: hidden; } .half { width: 48%; float: left; } .thri { width: 30%; float: left; } .all { width: 90%; float: left; } .td_select{ background-color: #c5c704!important; }
    </style>
</head>
<body>
<ul class="nav nav-tabs">
    <%--<li><a href="${ctx}/book/purchase/list">登到查询</a></li>--%>
    <li class="active"><a href="${ctx}/book/purchase/gotoEdit?batchId=${bkPurchaseBatch.batchId}">书籍登到</a></li>
</ul>
<br/>
<form:form id="purchaseForm" modelAttribute="bkPurchaseBatch" action="${ctx}/book/purchase/" method="post"
           class="form-horizontal">
    <form:input id="batchId" path="batchId" cssStyle="display: none;"/>
    <table style="width: 95%;" class="table table-striped table-bordered table-condensed">
        <tr>
            <th width="120">批次编号</th>
            <td>${bkPurchaseBatch.batchNumber}</td>
            <th width="120">创建时间</th>
            <td><fmt:formatDate value="${bkPurchaseBatch.planDate}" pattern="yyyy-MM-dd"/></td>
            <th width="120">验收时间</th>
            <td><input id="batchDate"
                       name="batchDate"
                       class="input-medium Wdate"
                       readonly="readonly"
                       maxlength="20"
                       type="text"
                       value="<fmt:formatDate value="${bkPurchaseBatch.batchDate}" pattern="yyyy-MM-dd HH:mm:ss"/>"
                       onclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false});"></td>
        </tr>
        <tr>
            <th width="120">备注</th>
            <td width="25%">
                <form:textarea id="remarks" path="remarks" htmlEscape="false" maxlength="30" cssStyle="height: 25px;width: 90%;" class="input-medium"/>
            </td>
            <td colspan="2">
                <%--<input class="btn btn-primary" type="button" style="margin-left: 30%;" onclick="refAddBookinfo()"--%>
                       <%--value="新增书目"/>--%>
            </td>
            <td colspan="2">
            </td>
        </tr>
    </table>

    <table id="contentTable" class="table table-striped table-bordered table-condensed">
        <thead>
        <tr>
            <th width="20">序号</th>
            <th>ISBN</th>
            <th>分类号</th>
            <th>题名</th>
            <th>著者</th>
            <th>丛编</th>
            <th>分册号</th>
            <th>出版社</th>
            <th>出版日期</th>
            <th>整套价格</th>
            <th>套数</th>
            <th width="20">操作</th>
        </tr>
        </thead>
        <tbody id="details">
        <c:forEach items="${bkPurchaseBatch.details}" var="info" varStatus="status">
            <c:if test="${info.mxArrived > 0}">
                <tr>
                    <td><input id="bkId_${info.bkId}" value="${info.bkId}" style="display: none;">${status.count}</td>
                    <td class="td_noselect">${info.bkIsbn}</td>
                    <td>${info.bkClass}</td>
                    <td>${info.bkName}<c:if test="${not empty info.othername}">-${info.othername}</c:if></td>
                    <td>${info.author}</td>
                    <td>${info.books}</td>
                    <td>${info.booksNum}</td>
                    <td>${info.publisher}</td>
                    <td>${info.pubdate}</td>
                    <td style="text-align: right;">${info.discountedPrice}</td>
                    <td style="text-align: right;">${info.mxArrived}</td>
                    <td width='150'>
                        <a href="javascript:addPurchase('${info.bkId}')">新增</a>&nbsp;&nbsp;
                        <a href="javascript:editPurchase('${info.batchId}', '${info.bkId}','${info.pbdId}')">编辑</a>&nbsp;&nbsp;
                            <%--<shiro:hasPermission name="book:purchase:delete">
                                <a href="javascript:deletePurchaseDetail('${info.pbdId}')">删除</a>&nbsp;&nbsp;
                            </shiro:hasPermission>--%>
                        <a href="javascript:printTagByDetails('${info.batchId}', '${info.bkId}','${info.pbdId}')">书标打印</a>
                    </td>
                </tr>
            </c:if>
        </c:forEach>
        <tr style="cursor: pointer;" ondblclick="openBookInfoEdit(0)" id="tr_0">
            <td></td>
            <td width="150">
                <input id="isbn_0" type="text" style="width: 150px;" name="isbn" onkeypress="EnterPress(this,event)">
                <input id="bkId_0" name="bkId" type="hidden">
            </td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td width="100"><input name="price" size="10" width="10" readonly="" style="width: 100px;background-color: #eeeeee;"></td>
            <td></td>
            <td width="200"><span></span><a href='javascript:deleteBookInfo("tr_0")'>删除</a>&nbsp;&nbsp;</td>
        </tr>
        </tbody>
    </table>
    <div class="form-actions">
        <c:if test="${bkPurchaseBatch.status eq 'work'}">
            <input id="addBatchButton" class="btn btn-primary" type="button" style="margin-left: 30%;" onclick="addBatchDetail()"
                   value="新增验收"/>
        </c:if>
            <%-- <c:if test="${bkPurchaseBatch.status ne 'ok'}">
                <input id="btnSubmit" class="btn btn-primary" type="button"
                       onclick="submitPurchase()" value="书籍登到"/>
            </c:if>
                <c:if test="${bkPurchaseBatch.status eq 'ok'}">
                     <input id="btnSubmit" class="btn btn-primary" type="button"
                            onclick="cancelPlan()" value="取消登到"/>
                 </c:if>--%>
    </div>
</form:form>
<object id="LODOP" classid="clsid:2105C259-1E0C-4534-8141-A753534CB4CA" width=0 height=0>
    <param name="Border" value="1">
    <param name="Color" value="white">
    <embed id="LODOP_EM" TYPE="application/x-print-lodop" width=0 height=0 border=0 Color="white"
           PLUGINSPAGE="install_lodop.exe">
</object>
<script type="text/javascript">
    function deletePurchaseDetail(pbdId) {
        $.ajax({
            type: "POST",
            url: "${ctx}/book/purchase/deleteDetail",
            data: {pbdId: pbdId},
            dataType: "json",
            success: function (data) {
                if (data.code == "0001") {
                    top.$.jBox.info(data.msg, '提示', {
                        closed: function () {
                            location.reload();
                        }
                    });
                    top.$('.jbox-body .jbox-icon').css('top', '55px');

                } else {
                    alertx("删除书籍验收信息失败");
                }
            }
        });
    }
    /**
     *  打印预览
     *//**
     *  打印预览
     */
    var LODOP;
    // 页面宽度
    var width = 210;
    var height = 297;
    $("#width").val(width);
    $("#height").val(height);

    var itemWidth = 43;
    var itemHeight = 16;
    $("#itemWidth").val(itemWidth);
    $("#itemHeight").val(itemHeight);

    // 上边距
    var itemTop = 0;
    var itemLeft = 40;
    $("#itemTop").val(itemTop);
    $("#itemLeft").val(itemLeft);

    // 每页多少个
    var pageNum = 40;

    var xMove = 165;
    var yMove = 95;
    $("#xMove").val(xMove);
    $("#yMove").val(yMove);

    function printTagByDetails(batchId, bkId, pbdId) {
        LODOP = getLodop(document.getElementById('LODOP'), document.getElementById('LODOP_EM'));
        LODOP.PRINT_INIT("打印");
        LODOP.SET_PRINT_PAGESIZE(1, width + "mm", height + "mm", "A4");

        $.ajax({
            type: "POST",
            url: "${ctx}/book/store/getStoresByBkId",
            data: {batch: batchId, bkId: bkId},
            dataType: "json",
            success: function (bookstores) {
                var k = 0;
                for (var i = 0; i < bookstores.length; i++) {
                    var store = bookstores[i];
                    var bar = "<div style='font-size: 18px;text-align: center;'>" +
                            "<div style='height:22px;'>" + store.classcode + "</div>" +
                            "<div style='height:22px;'>" + store.place + "</div>" +
                            "<div style='height:12px;font-size: 12px;'>" + store.banid + "</div>" +
                            "</div>";
                    // 翻页
                    if(i % pageNum == 0 && i>= pageNum){
                        k = 0;
                        LODOP.NewPage();
                    }

                    // 设置横移
                    var x = itemLeft + xMove * (k % 4);
                    // 设置竖移
                    var y = itemTop + yMove * Math.floor((k / 4));
                    // 打印 索书号和分类
                    LODOP.ADD_PRINT_HTM(y, x, itemWidth + "mm", itemHeight + "mm", bar);
                    k++;
                }
                LODOP.PRINT_DESIGN();
            }
        });
    }
</script>
</body>
</html>